package role

import (
	"context"
	"github.com/google/uuid"
	"github.com/kuangshp/go-utils/k"
	"insighttracking/apps/admin/auth"
	"insighttracking/common/utils"
	"insighttracking/query/model"
	"insighttracking/query/service"
	"net/http"

	"insighttracking/apps/admin/internal/svc"
	"insighttracking/apps/admin/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
	"os"
)

type GetRolePageApiLogic struct {
	logx.Logger
	ctx     context.Context
	svcCtx  *svc.ServiceContext
	Request *http.Request
}

func NewGetRolePageApiLogic(ctx context.Context, svcCtx *svc.ServiceContext, request *http.Request) *GetRolePageApiLogic {
	hostname, _ := os.Hostname()
	return &GetRolePageApiLogic{
		Logger: logx.WithContext(ctx).WithCallerSkip(0).WithFields(
			logx.Field("Log_UUID", uuid.New().String()),
			logx.Field("hostname", hostname)),
		ctx:     ctx,
		svcCtx:  svcCtx,
		Request: request,
	}
}

func (l *GetRolePageApiLogic) GetRolePageApi(req *types.GetRolePageReq) (resp *types.GetRolePageResp, err error) {
	// todo: add your logic here and delete this line
	accountInfo, err := auth.GetAccountInfo(l.svcCtx, l.Request)
	if err != nil {
		return &types.GetRolePageResp{
			Data: make([]types.RoleResp, 0),
			PageBaseResp: types.PageBaseResp{
				Total:      0,
				PageNumber: req.PageNumber,
				PageSize:   req.PageSize,
			},
		}, nil
	}
	roleEntities, count, err := service.RoleService.GetRolePageApi(l.ctx, accountInfo.EnterpriseId, req.Name, req.PageNumber, req.PageSize)
	if err != nil {
		return &types.GetRolePageResp{
			Data: make([]types.RoleResp, 0),
			PageBaseResp: types.PageBaseResp{
				Total:      0,
				PageNumber: req.PageNumber,
				PageSize:   req.PageSize,
			},
		}, nil
	}
	var result = k.Map(roleEntities, func(item *model.RoleEntity, index int) types.RoleResp {
		return types.RoleResp{
			ID:        item.ID,                                 // 主键id
			Name:      item.Name,                               // 角色名称
			Describe:  item.Describe,                           // 角色描述
			CreatedAt: utils.TimestampToString(item.CreatedAt), // 创建时间
			UpdatedAt: utils.TimestampToString(item.UpdatedAt), // 更新时间
		}
	})
	return &types.GetRolePageResp{
		Data: result,
		PageBaseResp: types.PageBaseResp{
			Total:      count,
			PageNumber: req.PageNumber,
			PageSize:   req.PageSize,
		},
	}, nil
}
